<template>
  <div class="add-member-level">
    <Row type='flex' justify="center">
      <Col>
        <Form ref="formInline" :model="formInline" :rules="ruleInline" :label-width="120">
          <FormItem prop="rightsName" label="权益名称：">
            <Row type="flex" align="middle">
              <Col>
                <Input type="text" @on-keyup="filterName" v-model="formInline.rightsName" placeholder="请输入" :maxlength="8" style="width:280px"></Input>
              </Col>
              <Col style="margin-left:10px;color: #808695"><span>最大长度为8个字</span></Col>
            </Row>
          </FormItem>
          <FormItem prop="instructions" label="权益简介：">
            <Row type="flex" align="middle">
              <Col>
                <Input type="text" @on-keyup="filterName" v-model="formInline.instructions" placeholder="请输入" :maxlength="20" style="width:280px"></Input>
              </Col>
              <Col style="margin-left:10px;color: #808695"><span>最大长度为20个字</span></Col>
            </Row>
          </FormItem>
          <FormItem prop="userRule" label="如何使用：">
            <Row type="flex" align="top">
              <div ref="addEditor" class="rich-editor"></div>
            </Row>
          </FormItem>
          <FormItem prop="memberLevelId" label="可用等级：">
            <Row type="flex" align="middle">
              <Col>
                <Select v-model="formInline.memberLevelId" style="width:180px">
                  <Option v-for="item in memberLevelList" :value="item.memberLevelId" :key="item.memberLevelId">V{{ item.memberLevel }}</Option>
                </Select>
              </Col>
              <Col style="margin-left:10px;color: #808695"><span>及以上等级可享用</span></Col>
            </Row>
          </FormItem>
          <FormItem label="上传图片：" prop="rightsImage" class="upload-img">
            <Row type="flex" align="top">
              <Col>
                <Upload ref="upload"
                    :format="['jpg','png']"
                    :max-size="50"
                    :on-success="handleSuccess"
                    :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize"
                    type="drag"
                    :show-upload-list="false"
                    :action="$config.uploadImg"
                    style="display: inline-block;width:96px;">
                  <img :src="formInline.rightsImage?formInline.rightsImage:defaultUrl"
                  style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                  alt="">
                </Upload>
                 <p v-if="formInline.rightsImage && imgloaded" class="replace_tit" @click="delHeadImage">删除</p>
              </Col>
              <Col>
                <div style="width:118px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;">支持格式：.jpg、.png<br>规格：50px*50px<br>大小：≤50K</div>
              </Col>
            </Row>
          </FormItem>
          <FormItem>
            <Button type="primary" style="width:100px" @click="handleSubmit('formInline')">确定</Button>
            <Button class="btn"
                  style="margin-left:20px;width:100px"
                  @click="closePage">取消</Button>
          </FormItem>
        </Form>
      </Col>
    </Row>
  </div>
</template>

<script>
import { saveMemberRights, getMemberLevelList } from '@/api/member/index'
import editor from '@/view/components/editor/mixins'
import { routeEqual } from '@/libs/util'
export default {
  name: 'member_rights_add',
  mixins: [editor],
  data () {
    return {
      memberLevelList: [],
      formInline: {
        memberLevelId: '0',
        rightsName: '',
        instructions: '',
        userRule: '',
        rightsImage: ''
      },
      ruleInline: {
        memberLevelId: [
          { required: true, message: '请选择可用等级', trigger: 'change' }
        ],
        rightsName: [
          { required: true, message: '权益名称不能为空', trigger: 'blur' }
        ],
        instructions: [
          { required: true, message: '权益简介不能为空', trigger: 'blur' }
        ],
        userRule: [
          { required: true, message: '如何使用不能为空' }
        ],
        rightsImage: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('上传图片不能为空'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      imgloaded: false,
      defaultUrl: require('@/assets/images/add.png')
    }
  },
  methods: {
    filterName () {
      this.formInline.rightsName = this.formInline.rightsName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/g, '')
      this.formInline.instructions = this.formInline.instructions.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/g, '')
      // this.formInline.userRule = this.formInline.userRule.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/g, '')
    },
    closePage () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'member_rights_list'
        })
      })
    },
    handleMaxSize (file) {
      this.$Message.warning('上传的图片大小不能超过50k')
    },
    handleFormatError (file) {
      this.$Message.warning('上传的图片格式错误')
    },
    handleSuccess (response, file, fileList) {
      var img = new Image()
      img.src = response.full_img_url
      var _this = this
      let temsrc = _this.formInline.rightsImage
      _this.formInline.rightsImage = response.full_img_url
      img.onload = function () {
        if (img.width !== 50 || img.height !== 50) {
          _this.$Message.warning('上传的图片规格不符')
          _this.formInline.rightsImage = temsrc
        } else {
          _this.imgloaded = true
          _this.formInline.rightsImage = response.full_img_url
        }
      }
    },
    delHeadImage () {
      this.formInline.rightsImage = ''
      this.imgloaded = false
    },
    handleSubmit () {
      if (this.$editor.txt.html().length > 2000) {
        this.$Message.error('如何使用不能超过2000个字符')
        return
      }
      this.$refs['formInline'].validate((valid) => {
        if (valid) {
          saveMemberRights({
            memberRights: '',
            memberLevelId: this.formInline.memberLevelId,
            merchantId: this.$store.state.user.merchantId,
            rightsName: this.formInline.rightsName,
            instructions: this.formInline.instructions,
            userRule: this.$editor.txt.html(),
            rightsImage: this.formInline.rightsImage,
            creatorId: this.$store.state.user.userId,
            creatorName: this.$store.state.user.userName
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('新增会员权益成功')
              this.closePage()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    }
  },
  created () {
    getMemberLevelList({
      merchantId: this.$store.state.user.merchantId
    }).then(res => {
      if (res.data.status === 200) {
        this.memberLevelList = res.data.data
        if (res.data.data.length > 0) {
          this.formInline.memberLevelId = res.data.data[0].memberLevelId
        }
      } else {
        this.$Message.error(`${res.data.error}`)
      }
    })
  },
  mounted () {
    this.createEditor(this.$refs.addEditor, () => {
      if (this.$editor.txt.html() === '<p><br></p>') {
        this.formInline.userRule = ''
      } else {
        this.formInline.userRule = this.$editor.txt.html()
      }
    })
  }
}
</script>

<style lang="less" scoped>
  .add-member-level{
    padding-top: 100px;
  }
  .replace_tit{
    position: absolute;
    left: 0;
    top: 72px;
    width: 96px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    opacity: 0.8;
    background: #ED4014;
    color: #fff;
  }
</style>
